package com.faiz.picturebed.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.faiz.picturebed.component.OssProperties;
import com.faiz.picturebed.entity.Picture;
import com.faiz.picturebed.mapper.PictureMapper;
import com.faiz.picturebed.service.PictureService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 图床 服务实现类
 * </p>
 *
 * @author faiz
 * @since 2021-07-14
 */
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    private final OssProperties ossProperties;

    private final PictureMapper pictureMapper;

    @Autowired
    public PictureServiceImpl(OssProperties ossProperties, PictureMapper pictureMapper) {
        this.ossProperties = ossProperties;
        this.pictureMapper = pictureMapper;
    }

    @Override
    public int batchInsertPicture(List<Picture> pictureList) {
        return 0;
    }

    @Override
    public int insertPicture(Picture picture) {
        return 0;
    }

    @Override
    public String uploadPicture(MultipartFile file) throws IOException {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = ossProperties.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        String bucketName = ossProperties.getBucketName();
        // 将上传的图片信息保存到数据库
        Picture picture = new Picture();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        InputStream inputStream = file.getInputStream();
        //1 为防止文件覆盖，需要加入文件随机值
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = file.getOriginalFilename();
        picture.setName(fileName);
        fileName = uuid + fileName;
        //2 把文件按照日期进行分类
        //获取当前日期
        String datePath = new DateTime().toString("yyyy/MM/dd");
        fileName = datePath + "/" + fileName;
        //第一个参数，bucket名称
        //第二个参数，上传到oss文件路径和文件名称 aa/bb/1.jpg
        //第三个参数，上传文件输入流
        ossClient.putObject(bucketName, fileName, inputStream);
        ossClient.shutdown();
        //https://edu-55555.oss-cn-beijing.aliyuncs.com/13.jpg
        String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
        picture.setUrl(url);
        pictureMapper.insert(picture);
        return url;
    }
}
